// static/js/grade_mgmt.js
(function(){
  let grades = [], editingId = null, adding = false;
  const msgEl  = document.getElementById('gradeMgmtMsg');
  const tbody  = document.getElementById('grade-tbody');
  const addBtn = document.getElementById('add-grade-btn');

  document.getElementById('gradeMgmtModal')
    .addEventListener('show.bs.modal', async ()=>{
      msgEl.style.display = 'none';
      grades = []; editingId = null; adding = false;
      addBtn.disabled = false;
      await loadGrades();
    });

  async function loadGrades(){
    try {
      const res = await fetch('/api/grades');
      if(!res.ok) throw new Error(res.status);
      grades = await res.json();
      renderGrades();
    } catch(e){
      showMsg('加载失败：'+e.message);
    }
  }

  function bindBlur(el, fn){
    el.addEventListener('blur', ()=>{
      if(!fn(el.value.trim())){
        el.classList.add('input-invalid');
        el.addEventListener('animationend', ()=>el.classList.remove('input-invalid'),{once:true});
      }
    });
  }

  function renderGrades(){
    tbody.innerHTML = '';
    // 普通行
    grades.forEach(g=>{
      if(editingId===g.id) return;
      const disabled = (adding||editingId!==null)?'disabled':'';
      const tr=document.createElement('tr');
      tr.innerHTML=`
        <td class="align-middle text-center">
          <span class="grade-name" data-bs-toggle="tooltip" title="${g.name}">
            ${g.name}
          </span>
        </td>
        <td class="text-center">
          <button class="btn btn-sm btn-outline-secondary me-1"${disabled}
                  onclick="moveGrade(${g.id},'up')" title="上移">
            <i class="bi bi-arrow-up"></i></button>
          <button class="btn btn-sm btn-outline-secondary me-1"${disabled}
                  onclick="moveGrade(${g.id},'down')" title="下移">
            <i class="bi bi-arrow-down"></i></button>
          <button class="btn btn-sm btn-outline-info me-1"${disabled}
                  onclick="enterEdit(${g.id})" title="编辑">
            <i class="bi bi-pencil-fill"></i></button>
          <button class="btn btn-sm btn-outline-danger"${disabled}
                  onclick="deleteGrade(${g.id})" title="删除">
            <i class="bi bi-trash-fill"></i></button>
        </td>`;
      tbody.appendChild(tr);
    });
    // 新增行
    if(adding){
      const tr=document.createElement('tr'); tr.id='new-row';
      tr.innerHTML=`
        <td class="align-middle text-center">
          <input type="text" id="new-input" class="form-control form-control-sm text-center">
        </td>
        <td class="text-center">
          <button class="btn btn-sm btn-outline-success me-1" onclick="saveNew()">
            <i class="bi bi-check-lg"></i></button>
          <button class="btn btn-sm btn-outline-secondary" onclick="cancelNew()">
            <i class="bi bi-x-lg"></i></button>
        </td>`;
      tbody.appendChild(tr);
      const inp=document.getElementById('new-input'); inp.focus();
      bindBlur(inp,v=>v!==''&&!grades.some(x=>x.name===v));
    }
    // 编辑行
    if(editingId!==null){
      const g=grades.find(x=>x.id===editingId);
      const tr=document.createElement('tr'); tr.id='edit-row';
      tr.innerHTML=`
        <td class="align-middle text-center">
          <input type="text" id="edit-input" class="form-control form-control-sm text-center" value="${g.name}">
        </td>
        <td class="text-center">
          <button class="btn btn-sm btn-outline-success me-1" onclick="saveEdit(${g.id})">
            <i class="bi bi-check-lg"></i></button>
          <button class="btn btn-sm btn-outline-secondary" onclick="cancelEdit()">
            <i class="bi bi-x-lg"></i></button>
        </td>`;
      const idx=grades.findIndex(x=>x.id===editingId);
      const rows=Array.from(tbody.children);
      if(rows.length===0||idx>=rows.length) tbody.appendChild(tr);
      else tbody.insertBefore(tr,rows[idx]);
      const inp=document.getElementById('edit-input'); inp.focus();
      bindBlur(inp,v=>v!==''&&!grades.some(x=>x.name===v&&x.id!==editingId));
    }
    // 初始化 Tooltip
    [...tbody.querySelectorAll('[data-bs-toggle="tooltip"]')]
      .forEach(el=>new bootstrap.Tooltip(el));
  }

  // 添加
  addBtn.addEventListener('click',()=>{
    if(adding||editingId!==null) return;
    adding=true; addBtn.disabled=true; renderGrades();
  });
  window.cancelNew=()=>{ adding=false; addBtn.disabled=false; renderGrades(); };
  window.saveNew=async ()=>{
    const v=document.getElementById('new-input').value.trim();
    if(!v) return showMsg('年级名不能为空');
    if(grades.some(x=>x.name===v)) return showMsg('年级名已存在');
    try{
      const res=await fetch('/api/grades',{method:'POST',
        headers:{'Content-Type':'application/json'},body:JSON.stringify({name:v})});
      const t=await res.text(),p=JSON.parse(t);
      if(!res.ok) throw new Error(p.error||p.message||t);
      adding=false; addBtn.disabled=false; await loadGrades();
    }catch(e){showMsg(e.message);}
  };

  // 编辑
  window.enterEdit=id=>{
    if(adding||editingId!==null) return;
    editingId=id; addBtn.disabled=true; renderGrades();
  };
  window.cancelEdit=()=>{ editingId=null; addBtn.disabled=false; renderGrades(); };
  window.saveEdit=async id=>{
    const v=document.getElementById('edit-input').value.trim();
    if(!v) return showMsg('年级名不能为空');
    if(grades.some(x=>x.name===v&&x.id!==id)) return showMsg('年级名已存在');
    try{
      const res=await fetch(`/api/grades/${id}`,{method:'PUT',
        headers:{'Content-Type':'application/json'},body:JSON.stringify({name:v})});
      const t=await res.text(),p=JSON.parse(t);
      if(!res.ok) throw new Error(p.error||p.message||t);
      editingId=null; addBtn.disabled=false; await loadGrades();
    }catch(e){showMsg(e.message);}
  };

  // 删除
  window.deleteGrade=async id=>{
    try {
      const res=await fetch(`/api/grades/${id}`,{method:'DELETE'});
      const t=await res.text(),p=JSON.parse(t);
      if(!res.ok) throw new Error(p.error||p.message||t);
      await loadGrades();
    }catch(e){showMsg('删除失败：'+e.message);}
  };

  // 移动
  window.moveGrade=async (id,dir)=>{
    try{
      await fetch(`/api/grades/${id}/move`,{
        method:'POST',headers:{'Content-Type':'application/json'},
        body:JSON.stringify({dir})
      });
      await loadGrades();
    }catch(e){showMsg('移动失败：'+e.message);}
  };

  function showMsg(msg){
    msgEl.textContent=msg; msgEl.style.display='inline';
    setTimeout(()=>msgEl.style.display='none',3000);
  }
})();
